package com.smart.nine.spel.expr.property;

import com.smart.nine.spel.expr.PlaceOfBirth;
import com.smart.nine.spel.expr.User;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Date;

/**
 * 对象属性解析
 *
 * @author junrui.wang
 * @create 2019/3/21
 */
public class PropertyExprSample {
    public static void main(String[] args) {
        User user = new User();
        user.setName("Tom");
        user.setLastVisit(new Date());
        user.setCredits(100);
        user.setPlaceOfBirth(new PlaceOfBirth("中国", "上海"));

        //解析上下文
        ExpressionParser expressionParser = new SpelExpressionParser();
        EvaluationContext evaluationContext = new StandardEvaluationContext(user);

        String name = expressionParser.parseExpression("name").getValue(evaluationContext, String.class);
        System.out.println(name);

        //对象属性名，首字母可以大写
        Integer credits = expressionParser.parseExpression("Credits + 10").getValue(evaluationContext, Integer.class);
        System.out.println(credits);

        String city = expressionParser.parseExpression("placeOfBirth.city").getValue(evaluationContext, String.class);
        System.out.println(city);

    }
}
